#![cfg_attr(
  all(not(debug_assertions), target_os = "windows"),
  windows_subsystem = "windows"
)]
mod cmd;
mod menu;
mod youdao;
use tauri::command;
use tauri::{
  async_runtime, http::ResponseBuilder, CustomMenuItem, GlobalShortcutManager, Manager, RunEvent,
  WindowBuilder, WindowUrl,
};


fn main() {
  // start composing a new Builder chain
  #[allow(unused_mut)]
  let mut app = tauri::Builder::default()
    .setup(|app| {
      // emit the `event-name` event to all webview windows on the frontend
      app
        .emit_all(
          "rust-event",
          cmd::Payload {
            message: "App From Backend Rust Event: Tauri is awesome!".into(),
          },
        )
        .unwrap();
      Ok(())
    })
    .on_page_load(|window, _| {
      let window_ = window.clone();
      println!("Called from on_page_load:{}", window.label());
    })
    .manage(cmd::Database {})
    .menu(menu::get_menu())
    // assign our generated "handler" to the chain
    .invoke_handler(
      // piece together application logic
      tauri::generate_handler![
        // attach the commands
        cmd::greet,
        cmd::log111,
        cmd::my_custom_command
      ],
    )
    .build(tauri::generate_context!())
    .expect("error while running tauri application");

  app.run(|app_handle, e| match e {
    // Application is ready (triggered only once)
    RunEvent::Ready => {
      let app_handle = app_handle.clone();
      // launch a new thread so it doesnt block any channel
      async_runtime::spawn(async move {
        let app_handle = app_handle.clone();
        app_handle
          .global_shortcut_manager()
          .register("CmdOrCtrl+1", move || {
            let app_handle = app_handle.clone();
            let window = app_handle.get_window("main").unwrap();
            window.set_title("New title!").unwrap();
          })
          .unwrap();
      });
    }

    // Keep the event loop running even if all windows are closed
    // This allow us to catch system tray events when there is no window
    RunEvent::ExitRequested { api, .. } => {
      api.prevent_exit();
    }
    _ => {}
  })
}
